package com.icen.utils.sensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class OrientationSensor implements SensorEventListener {

	private Context mContext;
	private Sensor mSensor = null;
	private SensorManager mSensorManager = null;
	private boolean mIsHasOrientationSensor = false;

	private static OrientationSensor mOrientationSensor = null;
	private OnOrientationSensorLinstener mOnOrientationSensorLinstener;

	private OrientationSensor(Context context) {
		this.mContext = context;
		this.initSensor();
	}

	public static OrientationSensor getInstance(Context context) {
		if (mOrientationSensor == null) {
			mOrientationSensor = new OrientationSensor(context);
		}
		return mOrientationSensor;
	}

	@SuppressWarnings("deprecation")
	private void initSensor() {
		mSensorManager = (SensorManager) mContext
				.getSystemService(Context.SENSOR_SERVICE);
		if (mSensorManager != null) {
			mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
		}
		if (mSensor == null) {
			mIsHasOrientationSensor = false;
		} else {
			mIsHasOrientationSensor = true;
		}
	}

	public void onStartSensor() {
		if (mIsHasOrientationSensor) {
			mSensorManager.registerListener(this, mSensor,
					SensorManager.SENSOR_DELAY_UI);
		}
	}

	public void onStopSensor() {
		if (mIsHasOrientationSensor) {
			mSensorManager.unregisterListener(this);
		}
	}

	private float lastX;
	private float lastY;
	private float lastZ;

	@SuppressWarnings("deprecation")
	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
			float dataX = event.values[SensorManager.DATA_X];
			float dataY = event.values[SensorManager.DATA_Y];
			float dataZ = event.values[SensorManager.DATA_Z];

			if (Math.abs(dataX - lastX) > 1.0 || Math.abs(dataY - lastY) > 1.0
					|| Math.abs(dataZ - lastZ) > 1.0) {
				if (mOnOrientationSensorLinstener != null) {
					mOnOrientationSensorLinstener.onOrientationChange(dataX,
							dataY, dataZ);
				}
			}
			lastX = dataX;
			lastY = dataY;
			lastZ = dataZ;
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	public void setOnOrientationSensorLinstener(
			OnOrientationSensorLinstener onOrientationSensorLinstener) {
		this.mOnOrientationSensorLinstener = onOrientationSensorLinstener;
	}

	public interface OnOrientationSensorLinstener {
		void onOrientationChange(float x, float y, float z);
	}

	public boolean isHas() {
		return mIsHasOrientationSensor;
	}

}
